package com.owlsmart.bluecat.api;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.owlsmart.bluecat.activity.LoginActivity;
import com.owlsmart.bluecat.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

/**
 * @author mingtai
 * @description
 * @time 2020/8/8 22:06
 */

public class Api {

    private static final String TAG = "Api";
    private static OkHttpClient client;

    private static String requestUrl;

    private static HashMap<String, Object> mParams;
    public static Api api = new Api();


    // 单例模式，私有化构造器
    public Api() {

    }

    public static Api config(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder().build();
        requestUrl = ApiConfig.BASE_ERL + url;
        mParams = params;
        return api;
    }

    public static Api assembleDoubanParams(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder().build();
        requestUrl = ApiConfig.DOUBAN_MOVIE + url;
        mParams = params;
        return api;
    }

    public static Api assembleMovieCommentParams(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder().build();
        requestUrl = ApiConfig.MOVIE_COMMENT_BASE + url;
        mParams = params;
        return api;
    }

    public void postRequest(Context context, final TitleCallback callback) {
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
        RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr);
        Request request = new Request.Builder().url(requestUrl).addHeader("contentType", "application/json;charset=UTF-8")
                .post(requestBodyJson).build();

        //    创建call回调，请求之后的返回，要知道成功了还是失败了，并且打印出来
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //    请求失败的处理
                callback.onFailure(e);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功的body
                final String result = response.body().string();
                callback.onSuccess(result);
            }
        });
    }

    public void getRequest(Context context, final TitleCallback callback) {
        String url = getAppendUrl(requestUrl, mParams);
        // SharedPreferences sp = context.getSharedPreferences("sp_ttit", MODE_PRIVATE);
        // String token = sp.getString("token", "");
        Log.d(TAG, "url = " + url + " 请求参数mParams = " + mParams);
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();

                // try {
                //     JSONObject jsonObject = new JSONObject(result);
                //     String code = jsonObject.getString("code");
                //     if (code.equals("401")) {
                //         Intent intent = new Intent(context, LoginActivity.class);
                //         context.startActivity(intent);
                //     }
                // } catch (JSONException e) {
                //     e.printStackTrace();
                // }

                callback.onSuccess(result);
            }
        });
    }

    private String getAppendUrl(String url, HashMap<String, Object> map) {

        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                if (StringUtils.isEmpty(buffer.toString())) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;
    }
}
